import _ from 'underscore'
import dispatcher from 'lib/dispatcher'
import {Scope} from 'lib/scopeFactory'

import TimeStore from 'lib/stores/time-store'
import {coreApi,sortMap,parseToChart} from '../apis/core-util'
// import tracelistApi from '../apis/tracelist'
import {tracelistApi,createGridOrder,parseToPartGrid} from '../apis/tracelist'

import CrashNameGrid from './CrashNameGrid.jsx';

export default class MainScope extends Scope {
  constructor(){
    super();
    this.$state = {
      totalNum:0,
      crashType: {
        label: '崩溃次数',     // 这里如果要更改成崩溃率的默认值，需要注意 RootView 的崩溃列表展示方式。
        value: 'crash_count'
      },
      displayHiddenItems: false,
      gridFilterOption: {
        fixed:null,
        follow:null,
        exec: function (data, property) {
          if(property === 'fixed') {
            this.fixed = this.fixed === null ? false : null;
          } else if (property === 'follow') {
            this.follow = this.follow === null ? true : null;
          }

          return _.chain(data)
            .filter((item) => this.fixed === null ? true : !item.fixed, this)
            .filter((item) => this.follow === null ? true : item.follow, this)
            .value();
        }
      },
      chart0:{
        loading:true
      },
      chart1:{
        loading:true
      },
      grid:{
        loading:true,
        getOrder:createGridOrder('count', -1)
        // getOrder:createGridOrder('appVersion', 1)
      },
      hiddenGridKey:Date.now(),
      hiddenGridColumns:_.map(CrashNameGrid.defaultProps.cols, value => _.extend({}, value)),
      hiddenGrid: {
        loading: true
      }
    }
    this.chart0Api = null;
    // this.chart0Api = coreApi({
    //   classify:'crashname',
    //   urlName:BlueWare.platform.toLowerCase()+'_crash_overview',
    //   customClassify:true,
    //   viewKey:'crash_count',
    //   order:'301'
    // },TimeStore.getValue);
    this.chart1Api = coreApi({
      urlName:BlueWare.platform.toLowerCase()+'_crash_series_data',
      classify:'appversion',
      viewKey:'crash_count',
      order:'303'
    },TimeStore.getValue);
    this.gridApi = coreApi({
      urlName:'custom/crash',
      // appVersionId:this.appVersionId,
      // deviceId:this.deviceId,
      // userIdentifier:this.userIdentifier,
      dataType:BlueWare.platform.toLowerCase()==='android'?1:2,
      limit:200,
    //   order:'appVersion',
    //   orderModel:'desc'
    // },TimeStore.getValue)
    },TimeStore.getValue,this.$state.grid.getOrder)
  }
  fetch(fetchAll = false){
    var _this = this;
    let isCrashCount = this.$state.crashType.value === 'crash_count',
        params = isCrashCount ? {
          classify:'crashname',
          urlName:BlueWare.platform.toLowerCase()+'_crash_overview',
          customClassify:true,
          viewKey:'crash_count',
          order:'301'
        } : {
          classify:'crashrate',
          urlName:BlueWare.platform.toLowerCase()+'_crash_rate',
          viewKey:'crash_rate_2',
          order:'301'
        };

      this.chart0Api = coreApi(params, TimeStore.getValue);

      this.chart0Api.fetch().then((data, params) => {
        let source = isCrashCount ? data.classifybyfixed : data.crashrate;

        // 崩溃次数
        if (isCrashCount) {
          this.$state.totalNum = _.chain(source.result).filter(function(s){
            return s.key.name === 'unfixed';
          }).pluck('combData').pluck('count').reduce(function(v1,v2){
            return v1+v2;
          },0).value();
        }

        this.$state.chart0 = {
          data: parseToChart(source, params)
        };
      },function(err){
        _this.$state.chart0 = {
          error:err
        }
      },function(params){
        _this.$state.chart0 = {
          loading:true,
          params:params
        }
        _this.emit()
      }).always(function(){
        _this.emit()
      });

    if (fetchAll) {
      this.chart1Api.fetch().then(function(data,params){
        _this.$state.chart1 = {
          data:parseToChart(data,params)
        }
      },function(err){
        _this.$state.chart1 = {
          error:err
        }
      },function(params){
        _this.$state.chart1 = {
          loading:true,
          params:params
        }
        _this.emit()
      }).always(function(){
        _this.emit()
      });

      this.gridApi.fetch().then((rawData,params) => {
        var datas = rawData;
        // var datas = rawData.data;
        _this.$state.grid = {
          data:_.filter(datas,(i) => !i.ignores && (_this.$state.onlyUnfixed?(!i.fix):true)),
          _data:_.filter(datas,(i) => !i.ignores)
        }
        _this.$state.hiddenGrid = {
          data:_.filter(datas,(i) => i.ignores)
        }
      },function(err){
        _this.$state.grid = {
          error:err
        }
      },function(params){
        _this.$state.grid = {
          loading:true,
          params:params
        }
        _this.emit()
      }).always(function(){
        _this.emit()
      });
    }
  }
  $toggle_filters(payload){
    this.$state.grid.data = this.$state.gridFilterOption.exec(this.$state.grid._data, payload.key);
    this.emit();
  }
  $toggle_hidden_items(payload){
    var display = this.$state.displayHiddenItems = !this.$state.displayHiddenItems;
    payload.e.target.innerText = display ? '隐藏' : '显示隐藏的崩溃';
    this.emit();
  }
  $resize_hidden_grid_columns_width(payload) {
    this.$state.hiddenGridKey = Date.now();
    this.$state.hiddenGridColumns = _.chain(this.$state.hiddenGridColumns)
                                     .zip(payload.widths)
                                     .map(item=>{
                                       item[0].width = item[1];
                                       delete item[0].containerStyle;
                                       return item[0];
                                     })
                                     .value();
    this.emit();
  }
  $settime(payload){
    this.fetch(true);
  }
  $load(){
    this.fetch(true);
  }
  $change_crash_type({crashType}) {
    this.$state.crashType = crashType;
    this.fetch(false);
  }
}
